#include "EditorContainer.h"
#include "MetaDataEditor.h"
#include <QHBoxLayout>
#include <QPainter>
#include <QLabel>
#include <QAxWidget>
#include "model/SWFTreeModel.h"
#include "swf/abc/ABCFile.h"
#include "swf/abc/AS3Model.h"
#include "swf/SWFTag.h"
#include "OpcodeEditor.h"
#include "qhexedit.h"
#include "Editor.h"
#include "swf/SWFEncoder.h"
#include "tags/DefineBitsEditor.h"
#include "tags/DisplayTagEditor.h"

EditorContainer::EditorContainer()
{
	this->init();
}

Editor* EditorContainer::openEditor( SWFTreeItem* source )
{
	auto itr = _editorMap.find(source);
	if (itr != _editorMap.end())
	{
		Editor* editor = itr->second;
		int idx = _tabView->indexOf(editor->asWidget());
		_tabView->setCurrentIndex(idx);
		return itr->second;
	}
	
	Editor* editor = nullptr;

	switch (source->getKind())
	{
	case SWFTreeItemKind::Method:
		{
			AS3Method* mbi = (AS3Method*) source->getUserData();
			AS3MethodBody* body = mbi->getBody();
			editor = new OpcodeEditor(mbi, this);
		}
		break;
	case SWFTreeItemKind::Tag:
		{
			SWFTagWrapper* wrapper = (SWFTagWrapper*) source->getUserData();
			SWFTag* tag = wrapper->getTag();
			if (tag->code == DefineBitsJPEG2 ||
				tag->code == DefineBitsJPEG3 ||
				tag->code == DefineBitsLossless ||
				tag->code == DefineBitsLossless2)
			{
				editor = new DefineBitsEditor(wrapper, this);
			}
			else if (tag->code == DefineButton2 ||
				tag->code == DefineShape ||
				tag->code == DefineShape2 ||
				tag->code == DefineShape3 ||
				tag->code == DefineShape4 ||
				tag->code == DefineText ||
				tag->code == DefineSprite)
			{
				editor = new DisplayTagEditor(wrapper, this);
			}
			else
			{
				auto hexEditor = new DefaultHexEditor(this);
				hexEditor->setData(QByteArray(tag->data, tag->length));
				editor = hexEditor;
			}
		}
		break;
	default:
		break;
	}

	if (editor != nullptr)
	{
		QWidget* widget = editor->asWidget();
		widget->setProperty("source", QVariant((int)source));

		int idx = _tabView->addTab(widget, editor->getEditorName());
		_tabView->setCurrentIndex(idx);
		_editorMap[source] = editor;
	}

	return nullptr;
}

void EditorContainer::init()
{
	QHBoxLayout* layout = new QHBoxLayout(this); 
	_tabView = new QTabWidget(this);
	_tabView->setTabsClosable(true);
	connect(_tabView, SIGNAL(tabCloseRequested(int)), this, SLOT(onTabCloseReq(int)));

	layout->addWidget(_tabView);
	layout->setContentsMargins(0, 0, 0, 0);
	this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
}

void EditorContainer::onTabCloseReq( int idx )
{
	QWidget* editor = _tabView->widget(idx);
	QVariant& v = editor->property("source");
	void* source = (void*) v.toInt();
	auto itr = _editorMap.find(source);
	if (itr != _editorMap.end())
	{
		_editorMap.erase(itr);
	}
	_tabView->removeTab(idx);
	delete editor;
}

